<template>
  <div :id='idname' style="height: 100%; width: 100%; background-color: white;"></div>
</template>

<script setup>

import * as echarts from 'echarts';
import { GridComponent,TooltipComponent } from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([GridComponent, LineChart, CanvasRenderer, UniversalTransition,TooltipComponent]);


import { useWaterData } from '@/store/Water/Water';
import { onMounted } from 'vue';

const chartData = useWaterData()
const props = defineProps(['id','title'])
const idname = 'chart' + props.id



function getTime(date){
let hour = String(new Date(date).getHours()).padStart(2, '0');  
let minute = String(new Date(date).getMinutes()).padStart(2, '0'); 
let second = String(new Date(date).getSeconds()).padStart(2, '0'); 
return hour+':'+minute
}
let length = 0

function getLastTime(){
let i = new Date()
let res = []

do{
  length++
  res.unshift(getTime(i))
  i-=3600000
}while(!(String(new Date(i).getHours()).padStart(2, '0')==='23'))

return res
}



onMounted(()=>{

var chartDom = document.getElementById(idname);
var myChart = echarts.init(chartDom)
var option;

option = {
tooltip:{
  trigger:'item',
  formatter: function (params) {   
          return  params.name + '<br/>' + params.value;  
      }, 
},
xAxis: {
  type: 'category',
  data: getLastTime()
},
yAxis: {
  type: 'value'
},
series: [
  {
    data: chartData.datas[chartData.chooseArea][chartData.time][props.id].slice(0,chartData.getLastTime(chartData.time).length),
    type: 'line'
  }
],
title:{
  text:props.title
}
};

chartData.$subscribe(()=>{
myChart.setOption({
  series:{
    data:chartData.datas[chartData.chooseArea][chartData.time][props.id].slice(0,chartData.getLastTime(chartData.time).length)
  },
  xAxis:{
    data:chartData.getLastTime(chartData.time)
  }
})
})

option && myChart.setOption(option);
window.addEventListener('resize',()=>{
myChart.resize()

})



})
</script>

<style>

</style>